package com.guigu.servicebusiness.controller;

import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private OSS ossClient;

    @RequestMapping("/oss")
    public String uploadOss(@RequestParam("file") MultipartFile file,String folder){
        String bucketName="qingcheng-lq";
        String fileName= folder+ "/"+ UUID.randomUUID()+ file.getOriginalFilename();
        try {
            ossClient.putObject(bucketName,fileName,file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "https://"+bucketName +".oss-cn-shenzhen.aliyuncs.com/"+fileName;

    }


    /**
     * 处理文件的本地上传请求
     * @return
     */
    @RequestMapping("/navtive")
    public String uploadnative(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        //要保存的本地服务器的目录
        String path =  request.getSession().getServletContext().getRealPath("img");
        String filePath = path + "/" + file.getOriginalFilename();

        File desFile = new File(filePath);

        if(!desFile.getParentFile().exists()){
            desFile.mkdirs();
        }

        try{
            file.transferTo(desFile);
        } catch(IOException ex){
            ex.printStackTrace();
        }

        return "http://localhost:9100/img/" + file.getOriginalFilename();

    }
}
